import {defineStore} from "pinia";
import {reactive, ref, type UnwrapNestedRefs, watch} from "vue";
import aiModelStore from "@/stores/aiModel";
import type QA from "@/models/QA";
import type Topic from '@/models/topic';
import {createTopic, getTopicDetail, getTopicList, getTopicMessages, sendAskMessage, setTopicTitle} from "@/apis/api";
import visitorStore from "@/stores/visitor";
import {TopicStatus} from "@/constants/TopicStatus";
import {socketListener} from "@/apis/socketIO";

const topicStore = defineStore('topicList', () => {
    const {getVisitorId} = visitorStore();

    const aiModel = aiModelStore();
    const topics: Topic[] = [];
    const  list = reactive(topics);
    let qaList: QA[] = [];
    const topic: UnwrapNestedRefs<Topic> = reactive<Topic>({
        topicId: null,
        title: '',
        qaList:qaList,
        status: TopicStatus.NONE
    });
    const  page = ref(1);
    const totalPage = ref(0);
    const pageSize = ref(0);
    const addTopic =async  () => {
        const  res = await createTopic('', getVisitorId())
        topic.topicId = res['topic_id'];
        topic.title = '';
        topic.startTime = new Date();
        topic.qaList = [];
        return topic;
    };
    const addQA = async (qa:QA) => {
        if(qa.qaId === undefined) {
            qa.askTime = new Date();
            qa.answerUserId = aiModel.ai;
            qa.askUserId = getVisitorId();
            qa.isNew = true;
        }else {
            qa.isNew = false;
        }
        qa.selected = false;
        if (topic.qaList === undefined) {
            topic.qaList = [];
        }
        if (!topic.topicId){
            topic.topicId = qa.topicId;
        }
        let index = topic.qaList.length;
        topic.qaList.push(qa);
        topic.status = TopicStatus.WAITING;
        if(qa.qaId === undefined) {
            sendAskMessage(topic.topicId, qa.askMessage, qa.askUserId).then(async (res) => {
                if(topic.qaList === undefined){
                    topic.qaList = [];
                }
                topic.qaList[index].qaId = res['qa_id'];
                topic.qaList[index].answerMessage = res['answer_message'];
                topic.qaList[index].answerMessageId = res['answer_message_id'];
                topic.qaList[index].askMessageId = res['ask_message_id'];
                if (topic.title === '') {
                    // 设置topic标题
                    const result = await setTopicTitle(topic.topicId??'',  res['ask_message'].substring(0, 16));
                    if (result) {
                        topic.title = result['title']??qa.askMessage.substring(0, 16);
                        const i: number = list.findIndex((t: Topic) => {
                            return t.topicId === topic.topicId
                        });
                        if (i > -1) {
                            list[i].title = topic.title;
                        }
                    }
                }
            });
        }
    }

    const initTopic = async () => {
        const res = await getTopicDetail(topic.topicId??'');
        topic.title = res['title']??'';
    }
    watch(()=> topic.topicId,  (topicId: any) => {
        addQaList(topicId);
        initTopic();
    });
    const addQaList = async (topicId: any) => {
        if(topicId){
            let res = await getTopicMessages(topicId);
            topic.qaList = [];
            for (const re of res['qa_list']) {
                const qa: QA = {
                    topicId: topicId,
                    qaId: re['qa_id'],
                    askMessage: re['ask_message'],
                    askMessageId: re['ask_message_id'],
                    answerMessageId: re['answer_message_id'],
                    askUserId: re['ask_user_id'],
                    answerMessage: re['answer_message'],
                    answerUserId: re['answer_user_id'],
                    askTime: re['ask_time'] ? new Date(re['ask_time']) : '',
                    answerTime: re['answer_time'] ? new Date(re['answer_time']) : '',
                    isNew: false,
                };
                await addQA(qa);
            }
        }
    }
    const loadTopicList = async () => {
        const res = await getTopicList(getVisitorId() ??'');
        list.splice(0, list.length);
        for (const re of res['topic_list']) {
            const l: QA[] = [];
            list.push({
                topicId: re['topic_id'],
                title: re['title'],
                message: re['message'],
                isActive: topic.topicId === re['topic_id'],
                qaList: l
            })
        }
    }

    const setAnswerMessage = (answerMessage: string, qaId:string) => {
        if(topic.qaList && topic.qaList.length > 0){
            let index: number = topic.qaList.findIndex((qa: QA) => {
                return qa.qaId === qaId;
            })?? -1;
            if (index > -1) {
                topic.qaList[index].answerMessage = answerMessage;
            }
        }
    }
    socketListener('ReceiveReanswerMessage', 'chat')((data: any) => {
        if(topic.qaList) {
            const index: number = topic.qaList.findIndex((qa:QA) => qa.qaId === data['qa_id']);
            if (index > -1) {
                topic.qaList[index].answerMessage = data['answer_message'];
            }
        }
    });
    return {list, page, totalPage, pageSize, topic, addTopic, addQA, loadTopicList, setAnswerMessage};
});

export default topicStore;